<?php
/**
 * @file
 * @package mileage
 * @version $Id$
**/

if (!defined('XOOPS_ROOT_PATH')) {
	exit;
}

if (!defined('MILEAGE_TRUST_PATH')) {
	define('MILEAGE_TRUST_PATH', XOOPS_TRUST_PATH . '/modules/' . $mytrustdirname);
}

require_once MILEAGE_TRUST_PATH . '/class/MileageUtils.class.php';

Mileage_AssetPreloadBase::prepare();


/**
 * Mileage_AssetPreloadBase
**/
class Mileage_AssetPreloadBase extends XCube_ActionFilter
{
	/**
	 * prepare
	 * 
	 * @param   void
	 * 
	 * @return  void
	**/
	public static function prepare()
	{
		$root =& XCube_Root::getSingleton();
		$instance = new Mileage_AssetPreloadBase($root->mController);
		$root->mController->addActionFilter($instance);
	}

	/**
	* preBlockFilter
	* 
	* @param   void
	* 
	* @return  void
	**/
	public function preBlockFilter()
	{
		$this->mRoot->mDelegateManager->add('Module.mileage.Global.Event.GetAssetManager','Mileage_AssetPreloadBase::getManager');
		$this->mRoot->mDelegateManager->add('Legacy_Utils.CreateModule','Mileage_AssetPreloadBase::getModule');
		$this->mRoot->mDelegateManager->add('Legacy_Utils.CreateBlockProcedure', 'Mileage_AssetPreloadBase::getBlock');
		$this->mRoot->mDelegateManager->add('Site.CheckLogin.Success', 'Mileage_AssetPreloadBase::login');
		$this->mRoot->mDelegateManager->add('Legacy.Event.RegistUser.Success', 'Mileage_AssetPreloadBase::register');
		$this->mRoot->mDelegateManager->add('Legacy_HelpAction.CreateHelpSmarty', 'Mileage_AssetPreloadBase::help');
	}

	/**
	* getManager
	* 
	* @param   Mileage_AssetManager  &$obj
	* @param   string  $dirname
	* 
	* @return  void
	**/
	public static function getManager(/*** Mileage_AssetManager ***/ &$obj,/*** string ***/ $dirname)
	{
		require_once MILEAGE_TRUST_PATH . '/class/AssetManager.class.php';
		$obj = Mileage_AssetManager::getInstance($dirname);
	}

	/**
	* getModule
	* 
	* @param   Legacy_AbstractModule  &$obj
	* @param   XoopsModule  $module
	* 
	* @return  void
	**/
	public static function getModule(/*** Legacy_AbstractModule ***/ &$obj,/*** XoopsModule ***/ $module)
	{
		if ($module->getInfo('trust_dirname') == 'mileage') {
			require_once MILEAGE_TRUST_PATH . '/class/Module.class.php';
			$obj = new Mileage_Module($module);
		}
	}

	/**
	 * getBlock
	 * 
	 * @param   Legacy_AbstractBlockProcedure  &$obj
	 * @param   XoopsBlock  $block
	 * 
	 * @return  void
	**/
	public static function getBlock(&$obj, $block)
	{
		$moduleHandler =& Mileage_Utils::getXoopsHandler('module');
		$module =& $moduleHandler->get($block->get('mid'));
		if (is_object($module) && $module->getInfo('trust_dirname') == 'mileage') {
			// Language blocks.php
			$root =& XCube_Root::getSingleton();
			$root->mLanguageManager->loadBlockMessageCatalog($module->getInfo('dirname'));
			// LOAD block file & Create OBJECT
			require_once MILEAGE_TRUST_PATH . '/blocks/' . $block->get('func_file');
			$className = 'Mileage_' . substr($block->get('show_func'), 4);
			$obj = new $className($block);
		}
	}

	/**
	 * login
	 * 
	 * @param   $root->mContext->mXoopsUser  $xoopsUser
	 * 
	 * @return  void
	**/
	public static function login($xoopsUser)
	{
		foreach ($GLOBALS['mileage_preload_dirname'] as $dirname) {
			if (preg_match("/[^a-zA-Z0-9_-]/", $dirname)) continue;
			self::getManager(&$asset, $dirname);
			if (!is_object($asset)) continue;
			$handlerMile =& $asset->getObject('handler', 'mile');
			if (!is_object($handlerMile)) continue;
			$objects =& $handlerMile->getObjects(new Criteria('url', 'login'));

			if (count($objects) > 0) {
				$root =& XCube_Root::getSingleton();

				foreach ($objects as $obj) {
					$interval = $obj->get('interval');
					$mile_id = $obj->get('mile_id');
					$point = $obj->get('point');

					$handlerRec =& $asset->getObject('handler', 'rec');
					$writeFlag = FALSE;
					if (Mileage_Utils::notExistsMileIDinRec($handlerRec, $mile_id, $interval, $xoopsUser->get('uid'), $dirname)) {
						$writeFlag = TRUE;
					}

					if ($writeFlag === TRUE) {
						// Rec Write
						require_once MILEAGE_TRUST_PATH . '/class/AbstractAction.class.php';
						require_once MILEAGE_TRUST_PATH . '/actions/RecEditAction.class.php';
						require_once MILEAGE_TRUST_PATH . '/class/AssetManager.class.php';

						$root->mLanguageManager->loadModuleMessageCatalog($dirname);// load lang main.php

						$mAction = new Mileage_RecEditAction();
						$mAction->mAsset = $asset;// interim

						self::_saveRec($mAction, $mile_id, $point, $dirname);
					}
				}//foreach $objects
			}// end if
		}// end foreach
	}

	/**
	 * register
	 * 
	 * @param   $root->mContext->mXoopsUser  $xoopsUser
	 * 
	 * @return  void
	**/
	public static function register($xoopsUser)
	{
		foreach ($GLOBALS['mileage_preload_dirname'] as $dirname) {
			if (preg_match("/[^a-zA-Z0-9_-]/", $dirname)) continue;
			self::getManager(&$asset, $dirname);
			if (!is_object($asset)) continue;
			$handlerMile =& $asset->getObject('handler', 'mile');
			if (!is_object($handlerMile)) continue;
			$objects =& $handlerMile->getObjects(new Criteria('url', 'register'));

			if (count($objects) > 0) {
				$root =& XCube_Root::getSingleton();

				foreach ($objects as $obj) {
					$interval = $obj->get('interval');
					$mile_id = $obj->get('mile_id');
					$point = $obj->get('point');

					$handlerRec =& $asset->getObject('handler', 'rec');

					if (Mileage_Utils::notExistsMileIDinRec($handlerRec, $mile_id, $interval, $xoopsUser->get('uid'), $dirname) === TRUE) {
						// Rec Write
						require_once MILEAGE_TRUST_PATH . '/class/AbstractAction.class.php';
						require_once MILEAGE_TRUST_PATH . '/actions/RecEditAction.class.php';
						require_once MILEAGE_TRUST_PATH . '/class/AssetManager.class.php';

						$root->mLanguageManager->loadModuleMessageCatalog($dirname);// load lang main.php

						$mAction = new Mileage_RecEditAction();
						$mAction->mAsset = $asset;// TODO
						if (!is_object($root->mContext->mXoopsUser) && is_object($xoopsUser)) {
							$root->mContext->mXoopsUser =& $xoopsUser;//TODO
						}

						self::_saveRec($mAction, $mile_id, $point, $dirname);
					}
				}// END foreach
			}// end if
		}// end foreach
	}

	public static function _saveRec($mAction, $mile_id, $point, $dirname) // ?
	{
		if ($mAction->prepare() === FALSE) {
			continue;
		}
	/*	if ($mAction->hasPermission() === FALSE) {
			continue;
		}*/

		$_POST['rec_id'] = 0;
		$_POST['mile_id'] = $mile_id;
		$_POST['point'] = $point;
		$_POST['dirname'] = $dirname;
		$mAction->mActionForm->load($mAction->mObject);

		$mAction->mActionForm->fetch();
		$mAction->mActionForm->validate_preload();

		if ($mAction->mActionForm->hasError()) {
			return;
		}

		$mAction->mActionForm->update($mAction->mObject);
		$mAction->mObjectHandler->insert($mAction->mObject);
	}

	/**
	 * help
	 * 
	 * @param   &$smarty
	 * 
	 * @return  
	**/
	public static function help(&$smarty) // ?
	{
		$dirname = xoops_getrequest('dirname');

		if (in_array($dirname, $GLOBALS['mileage_preload_dirname'])) {
			$dirname = preg_replace('/[^a-zA-Z0-9_-]/', '', $dirname);

			$root =& XCube_Root::getSingleton();
			$language = $root->mContext->getXoopsConfig('language');

			// load language file (main.php, admin.php)
			$root->mLanguageManager->loadModuleAdminMessageCatalog($dirname);
			$root->mLanguageManager->loadModuleMessageCatalog($dirname);

			$moduleHandler =& xoops_gethandler('module');
			$moduleObject =& $moduleHandler->getByDirname($dirname);
			$helpfile = xoops_getrequest('file') ? xoops_getrequest('file') : $moduleObject->getHelp();

			$smarty->setDirname($dirname);

			$template_dir = MILEAGE_TRUST_PATH . '/language/' . $language . '/help';
			if (!file_exists($template_dir . '/' . $helpfile)) {
				$template_dir = MILEAGE_TRUST_PATH . '/language/english/help';
				if (!file_exists($template_dir . '/' . $helpfile)) {
					$redirectUrl = XOOPS_URL . '/modules/'. $dirname . '/admin/index.php';
					$root->mController->executeRedirect($redirectUrl, 1, _AD_LEGACY_ERROR_NO_HELP_FILE);
				}
			}

			$smarty->template_dir = $template_dir;
			$smarty->assign('dirname', $dirname);
			$smarty->assign('mid', $moduleObject->getShow('mid'));
			$smarty->assign('altsys', file_exists(XOOPS_TRUST_PATH . '/libs/altsys/index.php'));
			$contents = $smarty->fetch('file:' . $helpfile);

			$renderer = $root->mContext->mModule->getRenderTarget();
			$renderer->setTemplateName('help.html');
			$module =& Legacy_Utils::createModule($moduleObject);
			$renderer->setAttribute('module', $module);
			$renderer->setAttribute('contents', $contents);

			$renderSystem =& $root->getRenderSystem('Legacy_AdminRenderSystem');
			$renderSystem->render($renderer);

			require_once XOOPS_ROOT_PATH . '/modules/legacy/kernel/Legacy_AdminControllerStrategy.class.php';
			$strategy = new Legacy_AdminControllerStrategy($root->mController);
			$root->mController->setStrategy($strategy);
			$root->mController->setupModuleContext();
			$root->mController->_mStrategy->setupModuleLanguage();
			require_once XOOPS_ROOT_PATH . '/header.php';
			print $renderer->getResult();
			require_once XOOPS_ROOT_PATH . '/footer.php';
			exit;
		}
	}
}
